import Taro, { getCurrentInstance } from '@tarojs/taro'
import { getPlatform, convertParamsToString, searchRouterKey } from '@UTILS/common'
import Scenes from './scenes'

const VerifyRouter = ['doctorList', 'doctorDetail', 'createConsultation',
  'payment', 'videoList', 'recommendDoctorList', 'customDoctorListTId', 'customDoctorListHId']

export interface RouteParams {
  [key: string]: string | boolean | undefined | Record<string, unknown>
}

function getFullUrl(key: string, params?: RouteParams) {
  const scene: string = Scenes[key]
  const prevScene = searchRouterKey(getCurrentInstance().router?.path)
  if (!scene) {
    throw Error(`Not found scene ->：[${scene}] !`)
  }
  if (params?.prevScene) {
    console.warn(`prevScene：[${scene}] !`)
  }
  let newParams = params
  if (getPlatform().isWX && VerifyRouter.indexOf(key) > -1) {
    newParams = { ...params || {}, isVerify: true }
  }
  newParams && Object.assign(newParams, { prevScene })
  return scene + convertParamsToString(newParams)
}

class NavigateManager {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  [key: string]: (p?: any, o?: any) => void;

  constructor() {
    this.createRouterFunc()
  }

  createRouterFunc = () => {
    // eslint-disable-next-line array-callback-return
    Object.keys(Scenes).map(key => {
      this[key] = (params: RouteParams, options?: Taro.navigateTo.Option) => {
        this.navigateTo(key, params, options)
      }
    })
  }

  switchTab = (key: string, options = {}) => Taro.switchTab({ ...options, url: getFullUrl(key) })

  reLaunch = (key: string, params: RouteParams, options = {}) => Taro.reLaunch({ ...options, url: getFullUrl(key, params) })

  redirectTo = (key: string, params: RouteParams = {}, options = {}) => Taro.redirectTo({ ...options, url: getFullUrl(key, params) })

  navigateTo = (key: string, params: RouteParams, options = {}) => Taro.navigateTo({ ...options, url: getFullUrl(key, params) })

  navigateBack = (delta = 1, options = {}) => Taro.navigateBack({ ...options, delta })
}

export default new NavigateManager()
